//
//  RTJPrepaymentController.m
//  RuiTaiJinProject
//
//  Created by jayson on 2019/4/1.
//  Copyright © 2019年 leewei. All rights reserved.
//

#import "RTJPrepaymentController.h"
#import "RTJBorrowingCell.h"
#import "RTJForgetPassWordController.h"
#import "RTJReimbursementView.h"
#import "LewPopupViewAnimationFade.h"

@interface RTJPrepaymentController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *data;
@property(nonatomic, assign) NSInteger currentPage;
@property (weak, nonatomic) IBOutlet UIButton *btn1;
@property (nonatomic, strong) NSDictionary *dic;
@property (nonatomic, strong) NSString *ids;
@property (weak, nonatomic) IBOutlet UIButton *btn2;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bg_viewHeight;
@end

@implementation RTJPrepaymentController

-(NSMutableArray *)data {
    if (!_data) {
        _data = [NSMutableArray array];
    }
    
    return _data;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.bg_viewHeight.constant = 0;
    self.btn1.hidden = YES;
    self.btn2.hidden = YES;
    
    _btn1.layer.cornerRadius = _btn1.height/2;
    _btn1.layer.masksToBounds = YES;
    _btn1.layer.borderColor = [UIColor colorForHex:@"#FFBC04"].CGColor;
    _btn1.layer.borderWidth = 1;
    
    _btn2.layer.cornerRadius = _btn2.height/2;
    _btn2.layer.masksToBounds = YES;
    
    self.tableView.tableFooterView=[UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    self.tableView.estimatedRowHeight=300;
    
    self.tableView.mj_header = [CustomRefreshGifHeader headerWithRefreshingBlock:^{
        
        [self loadData];
        
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

-(void)loadData{
    
    [SVProgressHUD  showWithStatus:nil];
    
    if(self.data.count == 0){
        
        [self.view showEmptyViewWithStr:@"" image:nil callback:nil];
    }
    
    [RTJNetWork asyncRequestWithURL:@"user/refund_detail" params:@{@"id":_binId} method:GET zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        [self.view removeEmptyView];
        
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                self.dic = data[@"data"];
                
                if (self.dic!=nil) {
                    
                    NSInteger deal_status = [self.dic [@"deal_status"]integerValue];
                    
                    self.bg_viewHeight.constant = deal_status==4 ? 64 :0;
                    self.btn1.hidden = deal_status==4 ? NO :YES;
                    self.btn2.hidden = deal_status==4 ? NO :YES;
                    
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    
                }else{
                    
                    
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                        
                    [self.view showEmptyViewWithStr:@"暂无相关数据" image:[UIImage imageNamed:@"kbylogo"] callback:^{
                            [self loadData];
                    }];
                        
                }
                
                [self.tableView reloadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
                [self.view showEmptyViewWithStr:data[@"msg"] image:[UIImage imageNamed:@"kbylogo"] callback:^{
                    [self loadData];
                }];
            }
            
        }else{
            
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            [self.view showEmptyViewWithStr:errorMsg image:[UIImage imageNamed:@"kbylogo"] callback:^{
                [self loadData];
            }];
            
        }
        
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    return _dic!=nil ? 1 + [_dic[@"loan_list"] count] : 0;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewAutomaticDimension;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * ID = @"RTJBorrowingCell";
    
    RTJBorrowingCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    
        
        if (indexPath.row == 0) {
            
            if (!cell) {
                
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJBorrowingCell" owner:self options:nil][2];
         
            }
            
            cell.borrowData = _dic;
            
        }else{
            
            if (!cell) {
                
            cell = [[NSBundle mainBundle] loadNibNamed:@"RTJBorrowingCell" owner:self options:nil][3];
        }
            cell.borrowData1 = _dic[@"loan_list"][indexPath.row-1];

    }
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return  cell;
    
}

/*
 *************************************
 提前还款
 *************************************
 */
- (IBAction)tiqian:(id)sender {
    
    [SVProgressHUD showWithStatus:nil];

    [RTJNetWork asyncRequestWithURL:@"user/advance_repay" params:@{@"id":_binId} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        
        if (success) {
            
            if ([data[@"status"]integerValue]==1) {
                
                [self showAlartView:data[@"data"]];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            
        }
        
    }];

}

-(void)showAlartView:(NSDictionary *)data{
    
    RTJReimbursementView *view = [RTJReimbursementView defaultViewWithFrame:CGRectMake(0, 0, 325, 280) data:data];
    view.parentVC = self;
    [self lew_presentPopupView:view animation:[LewPopupViewAnimationFade new] dismissed:^{
        
        NSLog(@"动画结束");
        
    }];
    
    [view withSureClick:^(NSString * _Nonnull pswStr) {
        
        [SVProgressHUD showWithStatus:nil];
        
        if (pswStr.length  == 0) {
            
            [SVProgressHUD showErrorWithStatus:@"请输入交易密码"];
            return ;
        }
        
        //验证支付密码是否正确
        [RTJNetWork asyncRequestWithURL:@"user/check_pay_password" params:@{@"pay_password":pswStr} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
            
            [SVProgressHUD dismiss];
            
            if (success) {
                
                if ([data[@"status"]integerValue]==1) {
                    
                    //提前还款
                    [ self prepayment:pswStr];
                    
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"密码错误:%@",data[@"msg"]]];
                }
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"密码错误:%@",errorMsg]];
                
            }
            
        }];
        
    }];
    
}


-(void)prepayment:(NSString *)password{
    
    [SVProgressHUD showWithStatus:nil];

    [RTJNetWork asyncRequestWithURL:@"user/inrepay_repay_borrow_money" params:@{@"paypassword":password,@"id":_binId} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        
        if (success) {
            
            if ([data[@"status"]integerValue]==1) {
                
                [SVProgressHUD showSuccessWithStatus:@"还款成功"];
                [self loadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            
        }
        
    }];
    
}

/*
 *************************************
 正常还款
 *************************************
 */
- (IBAction)huankuan:(id)sender {
    
    
    NSArray *arr = _dic[@"loan_list"];

    if ([arr isKindOfClass:[NSArray class]]&& arr.count!=0) {
        
           [arr enumerateObjectsUsingBlock:^(id  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        
            if ([dic[@"status"]integerValue] == 1) {
                
                self.ids = [NSString stringWithFormat:@"%@",dic[@"ids"]];
                
            }
            
        }];
        
        SpecialAlertView *special = [[SpecialAlertView alloc]initWithLevelType:YES];
        
        [special withSureClick:^(NSInteger tags,NSString *password,UIView *alertView) {
            
            [UIView animateWithDuration:0.3 animations:^{
                [alertView removeFromSuperview];
            }];
            
            if (tags == 110) {
                
//                [UIView animateWithDuration:0.3 animations:^{
//                    [alertView removeFromSuperview];
//                }];
                
                RTJForgetPassWordController *vc = [[RTJForgetPassWordController alloc]init];
                vc.isPayPassWord = YES;
                vc.title = @"找回支付密码";
                [self.navigationController pushViewController:vc animated:YES];
                
            }else{
                
                [SVProgressHUD showWithStatus:nil];

                if (password.length  == 0) {
                    
                    [SVProgressHUD showErrorWithStatus:@"请输入交易密码"];
                    return ;
                }
                //验证支付密码是否正确
                [RTJNetWork asyncRequestWithURL:@"user/check_pay_password" params:@{@"pay_password":password} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
                    
                    [SVProgressHUD dismiss];

                    if (success) {
                        
                        if ([data[@"status"]integerValue]==1) {
                            
//                            [UIView animateWithDuration:0.3 animations:^{
//                                [alertView removeFromSuperview];
//                            }];
                            
                            //开始进行还款
                            [self reimbursement:password];
                            
                        }else{
                            
                            
                            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"密码错误:%@",data[@"msg"]]];
                        }
                        
                    }else{
                        
                        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"密码错误:%@",errorMsg]];
                        
                    }
                }];
            }
        }];
    }
}

-(void)reimbursement:(NSString *)password{
    
    [SVProgressHUD  showWithStatus:nil];
    
    [RTJNetWork asyncRequestWithURL:@"user/repay_borrow_money" params:@{@"id":_binId,@"ids":_ids,@"paypassword":password} method:POST zxCompletion:^(id data, NSInteger status, BOOL success, NSString *errorMsg) {
        
        [SVProgressHUD dismiss];
        
        if (success) {
            
            if ([data[@"status"]integerValue] == 1) {
                
                [SVProgressHUD showSuccessWithStatus:@"还款成功"];
                [self loadData];
                
            }else{
                
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",data[@"msg"]]];
            }
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",errorMsg]];
            
        }
        
    }];
    
}
@end
